import { ref, reactive, computed } from "vue";
import { toast } from "@/util/util";

// 列表、分页、搜索、删除、修改状态
export function useInitTable(opt = {}) {

    let searchForm = {}
    let resetSearchForm = null
    if (opt.searchForm) {
        searchForm = reactive({ ...opt.searchForm })

        resetSearchForm = () => {
            for (const key in opt.searchForm) {
                searchForm[key] = opt.searchForm[key]
            }
            getListByAPI()
        }
    }


    const tableData = ref([]);
    const loading = ref(false);

    // 分页
    const currentPage = ref(1);
    const total = ref(0);
    const pageSize = ref(opt.pageSize);


    // 获取数据
    function getList(p = null) {
        if (typeof p == "number") {
            currentPage.value = p;
        }

        loading.value = true;
        searchForm['pageNo'] = currentPage.value
        searchForm['pageSize'] = pageSize.value
        opt.requestListAPI(searchForm)
            .then((res) => {
                if (opt.onGetListSuccess && typeof opt.onGetListSuccess == "function") {
                    opt.onGetListSuccess(res)
                } else {
                    tableData.value = res.results;
                    total.value = res.count;
                }
            })
            .finally(() => {
                loading.value = false;
            });
    }

    getList();

    // 修改激活状态
    const hanledStatus = (status, row) => {
        opt.updateStatus(row.id, status)
            .then((res) => {
                if (opt.onUpdateStatusSuccess && typeof opt.onUpdateStatusSuccess == "function") {
                    opt.onUpdateStatusSuccess(row, status)
                } else {
                    row.status = status;
                }
                toast("修改成功");

            })
            .finally(() => getList());
    };


    // 删除
    const handleDelete = (id) => {
        loading.value = true;
        opt.delete(id)
            .then((res) => {
                toast("删除成功");
                getList();
            })
            .finally(() => {
                loading.value = false;
            });
    };
    //  多选 选中id
    const multiSelectionIds = ref([]);
    const multipleTableRef = ref(null);
    const handleSelectionChange = (e) => {
        multiSelectionIds.value = e.map((o) => o.id);
    };
    // 批量删除
    const handleMultiDelete = () => {
        loading.value = true;
        opt.delete(multiSelectionIds.value)
            .then((res) => {
                toast("删除成功");
                if (multipleTableRef.value) {
                    multipleTableRef.value.clearSelection();
                }
                getList();
            })
            .finally(() => {
                loading.value = false;
            });
    };

    // 批量修改状态
    const handleMultiData = (id = null, data = null) => {
        loading.value = true;
        let ids = multiSelectionIds.value.length ? multiSelectionIds.value : id
        opt.upMultiData(ids, data)
            .then((res) => {
                toast("修改成功");
                if (multipleTableRef.value) {
                    multipleTableRef.value.clearSelection();
                }
                getList();
            })
            .finally(() => {
                loading.value = false;
            });
    };
    // 批量修改状态
    const handlePatchMultiSubmit = (id = null) => {
        loading.value = true;
        opt.upMultiSubmit(id)
            .then((res) => {
                toast("提交成功");
                getList();
            })
            .finally(() => {
                loading.value = false;
            });
    };
    return {
        searchForm,
        resetSearchForm,
        tableData,
        loading,
        currentPage,
        total,
        pageSize,
        getList,
        hanledStatus,
        handleDelete,
        multipleTableRef,
        handleSelectionChange,
        handleMultiDelete,
        handleMultiData,
        handlePatchMultiSubmit,
    }
}

// 新增、修改
export function useInitForm(opt = {}) {
    // 表单部分

    const formDrawerRef = ref(null);
    const formRef = ref(null);
    const defaultForm = opt.form
    const form = reactive({});
    const rules = opt.rules || {};
    const editId = ref(0);
    const drawerTitle = computed(() => (editId.value ? "修改" : "新增"));

    const handleSubmit = () => {
        formRef.value.validate((valid) => {
            if (!valid) return;

            formDrawerRef.value.showLoading();

            let body = {}
            if (opt.beforeSubmit && typeof opt.beforeSubmit == "function") {
                body = opt.beforeSubmit({ ...form })
            } else {
                body = form
            }
            const fun = editId.value ?
                opt.update(editId.value, body) :
                opt.create(body)
            fun.then((res) => {
                toast(drawerTitle.value + "成功");
                // 修改刷新当前页，新增刷新第一页
                opt.getList(editId.value ? false : 1);
                formDrawerRef.value.close();
            })
                .finally(() => {
                    formDrawerRef.value.hideLoading();
                });
        });
    };



    // 重置表单
    function resetForm(row = false) {
        if (formRef.value) formRef.value.clearValidate();
        if(row){
            for (const key in row) {
                form[key] = row[key];
            }
        }else{
            for (const key in defaultForm) {
                form[key] = row[key];
            }
        }
    }

    // 新增
    const handleCreate = () => {
        editId.value = 0;
        resetForm(defaultForm);
        formDrawerRef.value.open();
    };

    // 编辑
    const handleEdit = (row) => {
        editId.value = row.id;
        resetForm(row);

        formDrawerRef.value.open();
    };

    return {
        formDrawerRef,
        formRef,
        form,
        rules,
        editId,
        drawerTitle,
        handleSubmit,
        resetForm,
        handleCreate,
        handleEdit
    }
}